package com.fastjrun.codeg.javamapper;

import com.fastjrun.codeg.common.Common;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.AbstractJavaMapperMethodGenerator;

import java.util.Set;
import java.util.TreeSet;

public class CustomJavaMapperMethodGenerator extends AbstractJavaMapperMethodGenerator {

  @Override
  public void addInterfaceElements(Interface interfaze) {

    addInterfaceInsertBatch(interfaze);
  }

  private void addInterfaceInsertBatch(Interface interfaze) {
    Set<FullyQualifiedJavaType> importedTypes = new TreeSet();
    FullyQualifiedJavaType parameterType;
    if (introspectedTable.getRules().generateRecordWithBLOBsClass()) {
      parameterType = new FullyQualifiedJavaType(introspectedTable.getRecordWithBLOBsType());
    } else {
      parameterType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
    }
    importedTypes.add(parameterType);

    Method method = new Method(Common.INSERTBATCH);
    method.setVisibility(JavaVisibility.PUBLIC);
    method.setReturnType(FullyQualifiedJavaType.getIntInstance());

    method.addParameter(
        new Parameter(
            new FullyQualifiedJavaType(
                "java.lang.List<" + parameterType.getShortName() + ">"), // $NON-NLS-1$
            "records")); //$NON-NLS-1$

    FullyQualifiedJavaType fqjt =
        new FullyQualifiedJavaType(introspectedTable.getMyBatis3SqlProviderType());

    String s =
        "@InsertProvider(type=" //$NON-NLS-1$
            + fqjt.getShortName()
            + ".class, method=\"" //$NON-NLS-1$
            + Common.INSERTBATCH
            + "\")"; //$NON-NLS-1$
    method.addAnnotation(s);

    initMethod(interfaze, importedTypes, method);
  }

  private void initMethod(
      Interface interfaze, Set<FullyQualifiedJavaType> importedTypes, Method method) {
    context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
    interfaze.addImportedTypes(importedTypes);
    interfaze.addMethod(method);
    method.setAbstract(true);
  }
}
